<template>
	<view class="content-box">
		<!-- 头部navbar -->
		<navbar :fixed="true" :bgColor="'#fff'" :title="t('my.grxx')" :leftIcon="true"></navbar>
		<view class="content-bg">
			<!-- 标签切换 -->
			<view class="tab-container">
				<view class="tab-item" :class="{ active: activeTab === 'avatar' }" @click="switchTab('avatar')">
					{{t('my.tx2')}}
				</view>
				<view class="tab-item" :class="{ active: activeTab === 'username' }" @click="switchTab('username')">
					{{ t('my.yhm') }}
				</view>
				<view class="tab-item" :class="{ active: activeTab === 'email' }" @click="switchTab('email')">
					{{ t('my.yx') }}
				</view>
			</view>

			<!-- 头像选择区域 -->
			<view class="avatar-section" v-if="activeTab === 'avatar'">
				<!-- 当前选中的头像 -->
				<view class="selected-avatar">
					<image class="avatar-preview" :src="selectedAvatarUrl" :style="{ backgroundColor: selectedColor }"></image>
				</view>

				<!-- 选择头像 -->
				<text class="section-title">{{ t('my.xztx') }}</text>
				<view class="avatar-grid">
					<view v-for="index in 15" :key="index" class="avatar-item" :class="{ selected: selectedAvatar === index }"
						@click="selectAvatar(index)">
						<image class="avatar-image" :src="`/static/image/avatar/${index}.png`"
							:style="{ backgroundColor: selectedAvatar === index ? selectedColor : '' }"></image>
						<view class="check-icon" v-if="selectedAvatar === index"></view>
					</view>
				</view>

				<!-- 选择颜色 -->
				<text class="section-title">{{ t('my.xzys') }}</text>
				<view class="color-grid">
					<view v-for="(color, index) in colorList" :key="index" class="color-item" :style="{ backgroundColor: color }"
						:class="{ selected: selectedColor === color }" @click="selectColor(color)"></view>
				</view>
			</view>
			<!-- 用户名 -->
			<view class="username-section" v-if="activeTab === 'username'">
				<view class="user-form">
					<view class="form-item">
						<view class="label">{{t('my.dqyhm')}}</view>
						<view class="input-box readonly" :class="{active:userName}">
							<image src="/static/icon/user-icon.svg" mode=""></image>
							<input type="text" v-model="userName" :placeholder="t('my.qsrdqyhm')" readonly />
						</view>
					</view>
					<view class="form-item">
						<view class="label">{{t('my.xdyhm')}}</view>
						<view class="input-box" :class="{active:newUserName}">
							<image src="/static/icon/user-icon.svg" mode=""></image>
							<input type="text" v-model="newUserName" :placeholder="t('my.qsrxdyhm')" />
						</view>
					</view>
				</view>
				<view class="tip-box">
					{{t('my.mgyh24xsznxg1c')}}
				</view>
			</view>
			<!-- 邮箱 -->
			<view class="username-section" v-if="activeTab === 'email'">
				<view class="user-form">
					<view class="form-item">
						<view class="label">{{t('my.dqyx')}}</view>
						<view class="input-box readonly" :class="{active:email}">
							<image src="/static/icon/email-icon.svg" mode=""></image>
							<input type="text" v-model="email" :placeholder="t('my.qsrdqyx')" readonly />
						</view>
					</view>
					<view class="form-item" :class="{active:newEmail}">
						<view class="label">{{t('my.xyx')}}</view>
						<view class="input-box">
							<image src="/static/icon/user-icon.svg" mode=""></image>
							<input type="text" v-model="newEmail" :placeholder="t('my.qsrxyx')" />
						</view>
					</view>
				</view>
				<view class="tip-box">
					{{t('my.mgyh7tznxg1c')}}
				</view>
			</view>
		</view>
		<!-- 下一步按钮 -->
		<button v-if="activeTab === 'email'" class="confirm-btn" @click="nextBut">{{t('my.xyb')}}</button>
		<!-- 确认按钮 -->
		<button v-else class="confirm-btn" @click="confirmChanges">{{ t('common.confirm') }}</button>
		
		<GlobalPopup ref="popup"></GlobalPopup>
	</view>
</template>

<script setup>
	import {
		useI18n
	} from 'vue-i18n';
	import {
		ref,
		computed,
		onMounted
	} from 'vue';
	import { userApi, authApi } from '@/utils/api'
	const {
		t,
		locale
	} = useI18n();

	// 当前激活的标签
	const activeTab = ref('username');

	
	const popup = ref()
	// 切换标签
	const switchTab = (tab) => {
		activeTab.value = tab;
	};

	const userName = ref('') // 当前用户昵称（从页面参数获取，不可修改）
	const newUserName = ref('') // 新用户昵称（可修改）
	const email = ref('')
	const newEmail = ref('')
	
	// 页面加载时获取传递的昵称和邮箱参数
	onMounted(() => {
		const pages = getCurrentPages();
		const currentPage = pages[pages.length - 1];
		const options = currentPage.options;
		if (options.nickname) {
			userName.value = decodeURIComponent(options.nickname);
		}
		if (options.email) {
			email.value = decodeURIComponent(options.email);
		}
	});
	

	// 头像选择
	const selectedAvatar = ref(1); // 默认选择第一个头像

	// 颜色选择
	const colorList = [
		'#C5D3F1', // 浅蓝色
		'#C3EAC3', // 浅绿色
		'#A8E6E6', // 浅青色
		'#D7C5F0', // 浅紫色
		'#B8D1F9', // 浅蓝色
		'#D9D9D9', // 浅灰色
		'#C9CEB9', // 浅灰绿色
		'#ECC6F3', // 浅粉紫色
		'#F5F5C3', // 浅黄色
		'#D1E9D1' // 浅绿色
	];
	const selectedColor = ref(colorList[0]); // 默认选择第一个颜色

	// 选择头像
	const selectAvatar = (index) => {
		selectedAvatar.value = index;
	};

	// 选择颜色
	const selectColor = (color) => {
		selectedColor.value = color;
	};

	// 计算当前选中的头像URL
	const selectedAvatarUrl = computed(() => {
		return `/static/image/avatar/${selectedAvatar.value}.png`;
	});

	// 确认修改
	const confirmChanges = async () => {
		try {
			// 显示加载状态
			uni.showLoading({
				title: t('common.loading') || '加载中...'
			});

			let updateData = {};
			
			if (activeTab.value === 'avatar') {
				// 头像更新逻辑
				const frontendBaseUrl = window.location.origin; // 获取当前前端域名
				const avatarUrl = `${frontendBaseUrl}${selectedAvatarUrl.value}`;
				
				updateData = {
					avatar: avatarUrl,
					avatarBg: selectedColor.value
				};
			} else if (activeTab.value === 'username') {
				// 用户名更新逻辑
				if (!newUserName.value.trim()) {
					uni.hideLoading();
					popup.value.open({
						title: t('common.error') || '错误',
						content: '请输入新的用户名',
						success: false,
						loading: false,
					});
					return;
				}
				
				updateData = {
					nickname: newUserName.value.trim()
				};
			}

			// 调用API更新用户信息
			const response = await userApi.updateUserInfo(updateData);
			
			// 隐藏加载状态
			uni.hideLoading();

			// 显示成功提示
			popup.value.open({
				title: t('my.xgcg'),
				content: '',
				success: true,
				loading: false,
			});

		} catch (error) {
			// 隐藏加载状态
			uni.hideLoading();
			
			// 显示错误提示
			popup.value.open({
				title: t('common.error') || '错误',
				content: error.message || '更新失败，请重试',
				success: false,
				loading: false,
			});
			
			console.error('更新用户信息失败:', error);
		}
	};
	// 下一步
	const nextBut = async () => {
			// 验证新邮箱是否为空
			if (!newEmail.value.trim()) {
				uni.showToast({
					title: '请输入新邮箱地址',
					icon: 'none'
				})
				return
			}

			// 验证邮箱格式
			const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
			if (!emailRegex.test(newEmail.value)) {
				uni.showToast({
					title: '请输入正确的邮箱格式',
					icon: 'none'
				})
				return
			}

			try {
				const requestData = {
					email: newEmail.value,
					type: 0
				}
				console.log('发送验证码请求参数:', requestData)
				
				// 发送验证码到新邮箱
				const response = await authApi.sendMailCode(requestData)
				console.log('发送验证码响应:', response)

				uni.showToast({
					title: '验证码已发送',
					icon: 'success'
				})

				// 跳转到验证码页面，传递新邮箱参数
				const jumpUrl = `/pages/my/info/checkEmail?newEmail=${encodeURIComponent(newEmail.value)}`
				console.log('准备跳转到:', jumpUrl)
				console.log('传递的newEmail值:', newEmail.value)
				
				uni.navigateTo({
					url: jumpUrl
				})
			} catch (error) {
				console.error('发送验证码失败详细信息:', error)
				console.error('错误类型:', typeof error)
				console.error('错误内容:', JSON.stringify(error, null, 2))
				
				let errorMessage = '发送验证码失败，请重试'
				if (error && error.message) {
					errorMessage = error.message
				} else if (error && error.msg) {
					errorMessage = error.msg
				} else if (typeof error === 'string') {
					errorMessage = error
				}
				
				uni.showToast({
					title: errorMessage,
					icon: 'none',
					duration: 3000
				})
			}
		}
</script>

<style scoped lang="scss">
	.content-box {
		min-height: 100vh;
		background: rgba(245, 246, 250, 1);
		padding-bottom: 100rpx;
		box-sizing: border-box;

		.content-bg {
			border-radius: 31.4rpx;
			background: rgba(255, 255, 255, 1);
			box-shadow: 1.74rpx 1.74rpx 5.23rpx rgba(102, 102, 102, 0.25);
			margin: 27.91rpx 34.89rpx;
			padding: 68.03rpx 17.45rpx 109.9rpx 17.45rpx;
		}
	}

	/* 标签切换 */
	.tab-container {
		display: flex;
		justify-content: space-between;
		margin-bottom: 40rpx;

		.tab-item {
			padding: 20rpx 0;
			font-size: 38.37rpx;
			font-weight: 500;
			letter-spacing: 0rpx;
			line-height: 55.57rpx;
			color: rgba(51, 51, 51, 1);
			position: relative;
			flex: 1;
			text-align: center;

			&.active {
				color: #333333;
				font-weight: 500;

				&::after {
					content: '';
					position: absolute;
					bottom: 6.98rpx;
					left: 50%;
					transform: translateX(-50%);
					width: 52.33rpx;
					height: 6.98rpx;
					border-radius: 1742.54rpx;
					background: linear-gradient(90deg, rgba(12, 193, 155, 1) 0%, rgba(91, 220, 222, 1) 34.03%, rgba(5, 145, 198, 1) 65.97%, rgba(2, 120, 220, 1) 100%);
				}
			}
		}
	}

	/* 头像选择区域 */
	.avatar-section {
		margin-top: 38.38rpx;

		.selected-avatar {
			display: flex;
			justify-content: center;
			margin-bottom: 27.91rpx;

			.avatar-preview {
				width: 107.68rpx;
				height: 107.68rpx;
				border-radius: 50%;
			}
		}

		.section-title {
			display: block;
			font-size: 27.91rpx;
			font-weight: 400;
			letter-spacing: 0rpx;
			line-height: 40.42rpx;
			color: rgba(51, 51, 51, 1);
			margin-bottom: 17.45rpx;
		}

		.avatar-grid {
			// width: 100%;
			display: flex;
			justify-content: space-between;
			flex-wrap: wrap;
			padding: 26.17rpx 0 17.45rpx 17.45rpx;
			border-radius: 17.44rpx;
			background: rgba(245, 246, 250, 1);
			margin-bottom: 17.45rpx;

			.avatar-item {
				// width: 20%;
				// padding: 17.45rpx;
				// padding-right: 17.45rpx;
				// padding-bottom: 17.45rpx;
				// margin: ;
				margin-right: 17.45rpx;
				margin-bottom: 17.45rpx;
				// gap: 17.45rpx;
				box-sizing: border-box;
				position: relative;

				.avatar-image {
					width: 95.94rpx;
					height: 95.85rpx;
					border-radius: 50%;
				}

				.check-icon {
					position: absolute;
					right: 0rpx;
					bottom: 10rpx;
					width: 27.91rpx;
					height: 27.91rpx;
					border-radius: 50%;
					background: rgba(42, 130, 228, 1);
					display: flex;
					align-items: center;
					justify-content: center;
					border: 3.49rpx solid rgba(245, 246, 250, 1);

					&::after {
						content: '';
						width: 13.95rpx;
						height: 9.59rpx;
						border-left: 2rpx solid #FFFFFF;
						border-bottom: 2rpx solid #FFFFFF;
						transform: rotate(-45deg) translate(1rpx, -2rpx);
					}
				}
			}
		}

		.color-grid {
			display: flex;
			flex-wrap: wrap;
			justify-content: space-between;
			border-radius: 17.44rpx;
			background: rgba(245, 246, 250, 1);
			padding: 26.17rpx 0 17.45rpx 17.45rpx;

			.color-item {
				width: 101.17rpx;
				height: 101.17rpx;
				border-radius: 50%;
				box-sizing: border-box;
				margin-right: 17.45rpx;
				margin-bottom: 17.45rpx;

				&::after {
					content: '';
					display: block;
					width: 100%;
					padding-bottom: 100%;
					border-radius: 50%;
				}

				&.selected {
					position: relative;

					&::before {
						content: '';
						position: absolute;
						top: 50%;
						left: 50%;
						transform: translate(-50%, -50%);
						width: calc(100% + 1.74rpx);
						height: calc(100% + 1.74rpx);
						border: 1.74rpx solid rgba(42, 130, 228, 1);
						border-radius: 50%;
						box-sizing: border-box;
					}
				}
			}
		}
	}

	.username-section {
		margin: 71.52rpx 55.82rpx 0 55.82rpx;

		.user-form {

			.label {
				font-size: 24.42rpx;
				margin-bottom: 22.68rpx;
				color: rgba(51, 51, 51, 1);
				margin-left: 10.67rpx;
			}

			.input-box {
				display: flex;
				align-items: center;
				border-radius: 28.07rpx;
				background: rgba(249, 250, 251, 1);
				padding: 31.4rpx 62.29rpx;
				margin-bottom: 36.64rpx;
				border: 1.75rpx solid transparent;
				&.active{
					border-color: #3B82F6 ;
				}
				&.readonly {
					background: rgba(245, 246, 250, 1);
					input {
						color: rgba(102, 102, 102, 1);
					}
				}
			}

			image {
				width: 24.42rpx;
				height: 31.4rpx;
				margin-right: 50.59rpx;
			}

			input {
				color: rgba(51, 51, 51, 1);
				font-size: 27.91rpx;
			}
		}

		.tip-box {
			font-size: 24.42rpx;
			font-weight: 400;
			letter-spacing: 0rpx;
			line-height: 35.36rpx;
			color: rgba(102, 102, 102, 1);
			margin-top: 158.73rpx;
			// margin-bottom: 462.24rpx;
			text-align: center;
		}
	}

	/* 确认按钮 */
	.confirm-btn {
		width: 570.38rpx;
		height: 97.68rpx;
		line-height: 97.68rpx;
		border-radius: 26.16rpx;
		background: linear-gradient(90deg, rgba(12, 193, 155, 1) 0%, rgba(91, 220, 222, 1) 34.03%, rgba(5, 145, 198, 1) 65.97%, rgba(2, 120, 220, 1) 100%);
		color: #FFFFFF;
		font-size: 31.4rpx;
		font-weight: 500;
		display: flex;
		align-items: center;
		justify-content: center;
		margin-top: 57.57rpx;
	}
</style>

/**
* 6=10.67rpx
8=13.96rpx
10=17.45rpx
12=20.93rpx
13=22.68rpx
14=24.42rpx
15=26.17rpx
16=27.91rpx
17=29.65rpx

18=31.4rpx
20=34.89rpx
21=36.64rpx
22=38.38rpx
24=41.86rpx
25=43.61rpx
28=48.85rpx
29=50.59rpx
30=52.33rpx
32=55.82rpx
33=57.57rpx
35=61.06rpx
38=62.29rpx
39=68.03rpx
40=69.77rpx
41=71.52rpx
42=73.27rpx
43=75.01rpx
45=78.5rpx
49=85.47rpx
51=88.96rpx
52=90.70rpx
54=94.2rpx
84=146.52rpx
91=158.73rpx
194=338.4rpx
*/